<?php

namespace app\api\controller;

use app\admin\model\Carousel;
use app\api\model\Article;
use app\api\model\Category;
use app\api\model\Follow;
use app\api\model\User;
use app\BaseController;
use app\common\LogService;
use Exception;
use think\facade\Db;
use think\facade\Log;

class Index extends BaseController
{
    // 首页文章
    public function index()
    {
        $limit = input('limit', 10);
        if (!is_numeric($limit)) $limit = 10;
        $search = input('search');
        $cate_id = input('cate_id'); // 可能是一级分类ID或二级分类ID
        // lastest 最新  , hot 最热  , force 关注
        $sort = input('sort', 'latest'); // 排序方式，默认最新
        // 查询文章列表
        $list = Article::with(['category' => function ($query) {
            $query->field('id,cate_name,status');
            $query->where('status', 1);
        }, 'userInfo' => function ($query) {
            $query->field('id,nickname,avator');
        }])->hidden(['hide_content', 'reviewer_id', 'status', 'score', 'type', 'update_time', 'delete_time']);

        $uid = getUid();
        // 搜索条件
        if (!empty($search)) {
            LogService::record(
                user_id: $uid,
                name: '搜索文章',
                content: ['title' => $search]
            );
            $list->where('title', 'like', "%$search%");
        }

        // 判断传来的分类ID是一级还是二级
        if (!empty($cate_id)) {
            $category = Category::find($cate_id);
            if ($category) {
                if ($category->pid == 0) {
                    // 如果是一级分类，获取其下所有二级分类ID
                    $subCategoryIds = Category::where('pid', $cate_id)->column('id');
                    $list->whereIn('cate_id', $subCategoryIds);
                } else {
                    // 如果是二级分类，直接使用该分类ID
                    $list->where('cate_id', $cate_id);
                }
            }
            $list = $list->order('is_top asc , is_hot asc');
        }

        // 根据排序方式排序
        if ($sort == 'hot') {
            $list->where('heat', '>=', 100)->order('heat', 'desc');
        } else if ($sort == 'force' && $uid != 0) {
            $followId = Follow::where(['user_id' => $uid])->column('follow_id');
            $list->whereIn('user_id', $followId);
        } else {
            $list->order('create_time', 'desc');
        }
        // 分页
        $list = $list->where(['status' => 1])->paginate($limit);
        // 格式化时间
        $data = $list->toArray();

        foreach ($data['data'] as &$item) {
            $item['create_time'] = formatMessageTime($item['create_time']);
            $item['images'] = getFirstImageFromRichText($item['content']);
        }

        return success($data);
    }
    // 搜索用户
    public function searchUser($nickname)
    {
        if (empty($nickname)) {
            return error('搜索不能为空');
        }

        $currentUserId = getUid();

        $list = User::alias('u')
            // 左连接关注表，并带上当前用户的条件
            ->leftJoin('follow f', "f.follow_id = u.id AND f.user_id = $currentUserId AND f.relation_type = 1")
            // 模糊查询昵称
            ->where('u.nickname', 'like', "%" . $nickname . "%")
            // 选择字段并判断是否已关注
            ->field('u.id, u.nickname, u.signature, u.avator, 
                    IF(f.id IS NOT NULL, 1, 0) AS is_follow')
            ->paginate(10);
        LogService::record(
            user_id: getUid(),
            name: '搜索用户',
            content: ['nickname' => $nickname]
        );
        return success($list);
    }

    // 启动次数添加
    public function startUp()
    {
        $data = config('startUp');
        if ($data['date'] == date('d')) {
            $todayNum = ++$data['todayNum'];
        } else {
            $todayNum = 1;
        }
        $num = ++$data['num'];
        $today = intval(date('d'));
        $ctn = "
        <?php
           return [
                  'num' => $num
                ,'todayNum' => $todayNum
                ,'date' => $today
           ];";
        try {
            file_put_contents(app()->getRootPath() . 'app/api/config/startUp.php', $ctn);
        } catch (Exception $e) {
            Log::info("启动次数添加失败:" . $e->getMessage());
        }
    }
    // 获取配置
    public function config()
    {
        $upgrade = getConfig('admin', 'sys_upgrade');
        $notice = getConfig('admin', 'sys_notice');
        $main = getConfig('admin', 'sys_main');
        $link = getConfig('admin', 'sys_link');
        $data = [
            'upgrade' => $upgrade,
            'notice' => $notice,
            'main' => $main,
            'link' => $link
        ];
        return success($data);
    }
    public function carousel()
    {
        $list = Carousel::where(['status' => 1])->order('sort asc')->select();
        return success($list);
    }
}
